package com.pope.framework.metadata;

import com.pope.framework.core.util.StringUtil;
import com.pope.framework.util.TokenContext;

import cn.hutool.core.date.DateUtil;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.Constants;

import java.util.Objects;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;
@Component
public class OwnerCustomMetaObjectHandler implements  MetaObjectHandler {
	 @Override
	 public void insertFill(MetaObject metaObject) {
		  if(hasField(metaObject,"createtime")) {
				setFieldValByName("createtime", DateUtil.now(), metaObject);
			}
		  if(hasField(metaObject,"createMan")) {
				setFieldValByName("createMan",  StringUtil.toStr(TokenContext.getStaff()), metaObject);
			}
			if(hasField(metaObject,"updatetime")) {
				setFieldValByName("updatetime", DateUtil.now(), metaObject);
			}
			if(hasField(metaObject,"staffId")) {
				setFieldValByName("staffId", TokenContext.getStaff(), metaObject);
			}
			if(hasField(metaObject,"siteId")) {
				setFieldValByName("siteId", TokenContext.getSite(), metaObject);
			}
	    }

	    @Override
	    public void updateFill(MetaObject metaObject) {
	    	 
	    	if(hasField(metaObject,"updatetime")) {
				setFieldValByName("updatetime", DateUtil.now(), metaObject);
			}
			if(hasField(metaObject,"staffId")) {
				setFieldValByName("staffId", TokenContext.getStaff(), metaObject);
			}
			if(hasField(metaObject,"siteId")) {
				setFieldValByName("siteId", TokenContext.getSite(), metaObject);
			}
	    	
	    }
	    
	//判断是否有某字段
    protected boolean hasField(MetaObject metaObject,String fieldName) {
    	if (metaObject.hasGetter(fieldName)) {
            return true;
        } else if (metaObject.hasGetter(Constants.ENTITY_DOT + fieldName)) {
            return true;
        }
    	return false;
    }
    
}

